// Tailwind 配置
if (typeof tailwind !== 'undefined') {
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    primary: '#165DFF',
                    secondary: '#36CFC9',
                    success: '#52C41A',
                    warning: '#FAAD14',
                    danger: '#FF4D4F',
                    info: '#1890FF',
                    dark: '#1D2129',
                    'gray-light': '#F2F3F5',
                    'gray-medium': '#C9CDD4'
                },
                fontFamily: {
                    inter: ['Inter', 'system-ui', 'sans-serif'],
                },
            },
        }
    }
}

// 假数据仓库（用于接口失败时降级显示）
const MockData = {
    // 用户信息假数据
    userInfo: {
        data: {
            UserName: '管理员',
            UserNick: 'admin@example.com',
            UserAvatar: 'https://picsum.photos/id/1005/40/40'
        }
    },
    // 仪表盘数据假数据
    dashboardData: {
        todaySales: 24568,
        todayOrders: 1248,
        activeUsers: 32654,
        totalProducts: 8452,
        salesTrend: {
            labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            sales: [18500, 22400, 19800, 25600, 28900, 32400, 24568],
            orders: [850, 980, 890, 1120, 1350, 1580, 1248]
        },
        orderStatus: {
            labels: ['已完成', '配送中', '已付款', '已取消'],
            data: [65, 15, 12, 8]
        },
        recentOrders: [
            { id: '#ORD-85421', customer: '张三', avatar: 'https://picsum.photos/id/1027/32/32', amount: '¥298.00', status: '已完成', statusType: 'success', time: '2023-06-15 14:30' },
            { id: '#ORD-85420', customer: '李四', avatar: 'https://picsum.photos/id/1012/32/32', amount: '¥1,599.00', status: '配送中', statusType: 'warning', time: '2023-06-15 13:45' },
            { id: '#ORD-85419', customer: '王五', avatar: 'https://picsum.photos/id/1000/32/32', amount: '¥568.00', status: '已付款', statusType: 'info', time: '2023-06-15 11:20' },
            { id: '#ORD-85418', customer: '赵六', avatar: 'https://picsum.photos/id/1001/32/32', amount: '¥329.00', status: '已取消', statusType: 'danger', time: '2023-06-15 10:15' }
        ]
    },
    // 商品列表假数据
    products: [
        { id: 1, name: '高级无线蓝牙耳机', sku: 'PRO-2023-001', image: 'https://picsum.photos/id/26/80/80', category: '数码产品', price: '¥299.00', stock: 1254, status: '在售', statusType: 'success' },
        { id: 2, name: '智能手表 Pro', sku: 'WATCH-2023-005', image: 'https://picsum.photos/id/96/80/80', category: '智能设备', price: '¥899.00', stock: 568, status: '在售', statusType: 'success' },
        { id: 3, name: '男士纯棉T恤', sku: 'CLOTH-2023-102', image: 'https://picsum.photos/id/20/80/80', category: '服装鞋帽', price: '¥89.00', stock: 2456, status: '在售', statusType: 'success' },
        { id: 4, name: '复古机械键盘', sku: 'COMP-2023-056', image: 'https://picsum.photos/id/119/80/80', category: '电脑配件', price: '¥399.00', stock: 0, status: '缺货', statusType: 'gray' }
    ]
};

// API服务类（增强版，支持失败降级）
class ApiService {
    constructor() {
        // API基础URL
        this.baseUrl = '/api';
        // 请求超时时间（5秒）
        this.timeout = 5000;
        // 请求头配置
        this.headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
        };
    }

    /**
     * 通用请求方法（带超时和失败降级处理）
     * @param {string} url 请求URL
     * @param {string} method 请求方法
     * @param {object} data 请求数据
     * @param {object} mockData 降级假数据
     * @returns {Promise}
     */
    async request(url, method = 'GET', data = null, mockData = null) {
        // 创建超时Promise
        const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => {
                reject(new Error('请求超时'));
            }, this.timeout);
        });

        // 创建请求Promise
        const requestPromise = new Promise(async (resolve, reject) => {
            const options = {
                method,
                headers: this.headers,
                credentials: 'include' // 包含cookie信息
            };

            // 如果有数据，添加到请求体
            if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
                options.body = JSON.stringify(data);
            }

            // 如果是GET请求，处理参数
            let requestUrl = `${this.baseUrl}${url}`;
            if (data && method === 'GET') {
                const queryString = new URLSearchParams(data).toString();
                requestUrl += `?${queryString}`;
            }

            try {
                const response = await fetch(requestUrl, options);

                // 处理HTTP错误状态
                if (!response.ok) {
                    throw new Error(`HTTP错误状态: ${response.status}`);
                }

                // 解析响应（支持JSON和非JSON响应）
                const contentType = response.headers.get('content-type');
                let result;
                if (contentType && contentType.includes('application/json')) {
                    result = await response.json();
                } else {
                    result = await response.text();
                }

                resolve(result);
            } catch (error) {
                console.error(`[API错误] ${url}:`, error.message);
                // 如果有假数据，则返回假数据作为降级方案
                if (mockData !== null && mockData !== undefined) {
                    console.warn(`[API降级] 使用假数据: ${url}`);
                    resolve(mockData);
                } else {
                    reject(error);
                }
            }
        });

        // 竞速：谁先完成就返回谁（超时或正常响应）
        return Promise.race([requestPromise, timeoutPromise])
            .catch(error => {
                console.error(`[API超时] ${url}:`, error.message);
                // 超时情况下也返回假数据
                if (mockData !== null && mockData !== undefined) {
                    console.warn(`[API降级] 使用假数据: ${url}`);
                    return mockData;
                }
                throw error;
            });
    }

    // 获取用户信息（带降级）
    getUserInfo() {
        return this.request('/welcome-info', 'GET', null, MockData.userInfo)
            .then(data => {
                // 统一数据格式（处理接口返回和假数据的一致性）
                const userData = data.data || data;
                return {
                    data: {
                        UserName: userData.UserName || '管理员',
                        UserNick: userData.UserNick || 'admin@example.com',
                        UserAvatar: userData.UserAvatar || MockData.userInfo.data.UserAvatar
                    }
                };
            });
    }

    // 获取仪表盘数据（带降级）
    getDashboardData() {
        return this.request('/dashboard', 'GET', null, MockData.dashboardData)
            .then(data => {
                // 统一数据格式
                return {
                    todaySales: data.todaySales || MockData.dashboardData.todaySales,
                    todayOrders: data.todayOrders || MockData.dashboardData.todayOrders,
                    activeUsers: data.activeUsers || MockData.dashboardData.activeUsers,
                    totalProducts: data.totalProducts || MockData.dashboardData.totalProducts,
                    salesTrend: data.salesTrend || MockData.dashboardData.salesTrend,
                    orderStatus: data.orderStatus || MockData.dashboardData.orderStatus,
                    recentOrders: data.recentOrders || MockData.dashboardData.recentOrders
                };
            });
    }

    // 获取商品列表（带降级）
    getProducts(params = {}) {
        return this.request('/products', 'GET', params, { list: MockData.products, total: 125 })
            .then(data => {
                // 统一数据格式（适配分页场景）
                return {
                    list: data.list || data || MockData.products,
                    total: data.total || 125,
                    page: params.page || 1,
                    pageSize: params.pageSize || 10
                };
            });
    }

    // 获取订单列表（带降级）
    getOrders(params = {}) {
        return this.request('/orders', 'GET', params, { list: MockData.dashboardData.recentOrders, total: 500 })
            .then(data => {
                return {
                    list: data.list || data || MockData.dashboardData.recentOrders,
                    total: data.total || 500,
                    page: params.page || 1,
                    pageSize: params.pageSize || 10
                };
            });
    }

    // 退出登录接口
    loginOut() {
        return this.request('/LoginOut', 'GET', null, { success: true })
            .then(data => {
                return data.success !== false; // 即使接口返回错误，也默认认为退出成功
            });
    }

    // 其他接口
    getProduct(id) {
        const mockProduct = MockData.products.find(p => p.id === id) || MockData.products[0];
        return this.request(`/products/${id}`, 'GET', null, mockProduct);
    }

    createProduct(data) {
        return this.request('/products', 'POST', data, { success: true, id: Date.now() });
    }

    updateProduct(id, data) {
        return this.request(`/products/${id}`, 'PUT', data, { success: true });
    }

    deleteProduct(id) {
        return this.request(`/products/${id}`, 'DELETE', null, { success: true });
    }

    updateOrderStatus(id, status) {
        return this.request(`/orders/${id}/status`, 'PATCH', { status }, { success: true });
    }
}

// 页面加载完成后执行初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始初始化...');
    
    // 初始化API服务
    const apiService = new ApiService();

    // 初始化用户信息（优先接口，失败显示假数据）
    initUserInfo(apiService);

    // 初始化侧边栏导航（修复版）
    initSidebarNavigation();

    // 初始化模态框控制
    initModalControl();

    // 初始化按钮功能
    initButtonFunctions();

    // 初始化用户菜单交互
    initUserMenu();

    // 加载仪表盘数据（带降级）
    loadDashboardData(apiService);

    // 加载商品列表数据（带降级）
    loadProductsData(apiService);
});

// 初始化用户信息（支持接口降级）
function initUserInfo(apiService) {
    apiService.getUserInfo()
        .then(result => {
            const userData = result.data;
            console.log('用户信息加载成功:', userData);
            // 更新UI显示
            document.getElementById('user-name').textContent = userData.UserName;
            document.getElementById('user-email').textContent = userData.UserNick;
            document.getElementById('user-avatar').src = userData.UserAvatar;
            document.getElementById('user-avatar').alt = userData.UserName;
        })
        .catch(error => {
            console.error('用户信息加载失败，使用默认值:', error);
            // 显示默认假数据
            const defaultUser = MockData.userInfo.data;
            document.getElementById('user-name').textContent = defaultUser.UserName;
            document.getElementById('user-email').textContent = defaultUser.UserNick;
            document.getElementById('user-avatar').src = defaultUser.UserAvatar;
        });
}

// 修复后的侧边栏导航初始化函数
function initSidebarNavigation() {
    // 1. 检查关键元素是否存在
    const sidebar = document.getElementById('sidebar');
    const toggleBtn = document.getElementById('toggle-sidebar');
    const sidebarItems = document.querySelectorAll('.sidebar-item');
    const viewContents = document.querySelectorAll('.view-content');

    // 输出调试信息
    console.log('侧边导航初始化调试:');
    console.log('侧边栏元素:', sidebar ? '找到' : '未找到');
    console.log('切换按钮:', toggleBtn ? '找到' : '未找到');
    console.log('导航项数量:', sidebarItems.length);
    console.log('视图数量:', viewContents.length);

    // 2. 如果核心元素缺失，终止执行并提示
    if (!sidebar || !toggleBtn || sidebarItems.length === 0 || viewContents.length === 0) {
        console.error('导航初始化失败: 缺少必要的HTML元素');
        return;
    }

    // 3. 为每个导航项绑定点击事件
    sidebarItems.forEach((item, index) => {
        // 先移除所有可能的旧事件
        item.onclick = null;
        
        // 绑定新事件
        item.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            
            console.log(`点击了导航项 #${index}:`);
            console.log(`- 文本: ${this.textContent.trim()}`);
            console.log(`- 目标视图: ${this.getAttribute('data-target')}`);

            // 获取目标视图ID
            const targetId = this.getAttribute('data-target');
            if (!targetId) {
                console.error('当前导航项没有设置data-target属性');
                alert('导航配置错误: 缺少目标视图ID');
                return;
            }

            // 查找目标视图
            const targetView = document.getElementById(targetId);
            if (!targetView) {
                console.error(`未找到ID为"${targetId}"的视图元素`);
                alert(`无法找到页面内容: ${targetId}`);
                return;
            }

            // 4. 更新导航项选中状态
            sidebarItems.forEach(navItem => {
                navItem.classList.remove('active');
            });
            this.classList.add('active');

            // 5. 更新视图显示状态
            viewContents.forEach(view => {
                view.classList.add('hidden');
            });
            targetView.classList.remove('hidden');
            console.log(`已显示视图: ${targetId}`);

            // 6. 加载对应视图的数据
            const apiService = new ApiService();
            switch(targetId) {
                case 'dashboard-view':
                    loadDashboardData(apiService);
                    break;
                case 'products-view':
                    loadProductsData(apiService);
                    break;
                case 'orders-view':
                    loadOrdersData(apiService);
                    break;
                default:
                    console.log(`视图"${targetId}"无需加载额外数据`);
            }

            // 7. 移动设备上自动隐藏侧边栏
            if (window.innerWidth < 1024) {
                sidebar.classList.add('-translate-x-full');
            }
        }, true); // 使用捕获模式确保事件被触发
    });

    // 8. 侧边栏切换按钮功能
    toggleBtn.addEventListener('click', function(e) {
        e.preventDefault();
        sidebar.classList.toggle('-translate-x-full');
        console.log('侧边栏切换:', sidebar.classList.contains('-translate-x-full') ? '隐藏' : '显示');
    });

    // 9. 初始化默认显示的视图
    const defaultItem = document.querySelector('.sidebar-item.active');
    if (defaultItem) {
        const defaultTarget = defaultItem.getAttribute('data-target');
        if (defaultTarget) {
            const defaultView = document.getElementById(defaultTarget);
            if (defaultView) {
                viewContents.forEach(view => view.classList.add('hidden'));
                defaultView.classList.remove('hidden');
                console.log(`初始化默认视图: ${defaultTarget}`);
            }
        }
    }
}

// 初始化模态框控制
function initModalControl() {
    const modal = document.getElementById('product-modal');
    const openModalButtons = document.querySelectorAll('.btn-primary:has(.fa-plus)');
    const closeModalButtons = [document.getElementById('close-modal'), document.getElementById('cancel-modal')];

    openModalButtons.forEach(button => {
        button.addEventListener('click', function() {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            document.body.style.overflow = 'hidden';
        });
    });

    closeModalButtons.forEach(button => {
        if (button) {
            button.addEventListener('click', function() {
                modal.classList.add('hidden');
                modal.classList.remove('flex');
                document.body.style.overflow = '';
            });
        }
    });

    // 点击模态框外部关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            document.body.style.overflow = '';
        }
    });
}

// 初始化按钮功能
function initButtonFunctions() {
    // 前往商城按钮功能
    document.getElementById('goto-shop').addEventListener('click', function() {
        const shopUrl = '/shop'; // 商城前台地址
        window.open(shopUrl, '_blank');
    });

    // 前往采集按钮功能
    document.getElementById('goto-collect').addEventListener('click', function() {
        const collectUrl = '/task/collect'; // 采集页面地址
        window.open(collectUrl, '_blank');
    });
}

// 初始化图表（支持动态数据）
function initCharts(dashboardData = null) {
    // 使用传入的数据或假数据
    const data = dashboardData || MockData.dashboardData;
    
    // 销售趋势图表
    const salesCtx = document.getElementById('salesChart')?.getContext('2d');
    if (salesCtx) {
        // 销毁已存在的图表实例
        if (window.salesChartInstance) {
            window.salesChartInstance.destroy();
        }
        
        window.salesChartInstance = new Chart(salesCtx, {
            type: 'line',
            data: {
                labels: data.salesTrend.labels,
                datasets: [
                    {
                        label: '销售额',
                        data: data.salesTrend.sales,
                        borderColor: '#165DFF',
                        backgroundColor: 'rgba(22, 93, 255, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: '订单量',
                        data: data.salesTrend.orders,
                        borderColor: '#36CFC9',
                        backgroundColor: 'transparent',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '销售额 (¥)'
                        }
                    },
                    y1: {
                        beginAtZero: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: '订单量'
                        },
                        grid: {
                            drawOnChartArea: false
                        }
                    }
                }
            }
        });
    }

    // 订单状态图表
    const orderStatusCtx = document.getElementById('orderStatusChart')?.getContext('2d');
    if (orderStatusCtx) {
        // 销毁已存在的图表实例
        if (window.orderStatusChartInstance) {
            window.orderStatusChartInstance.destroy();
        }
        
        window.orderStatusChartInstance = new Chart(orderStatusCtx, {
            type: 'doughnut',
            data: {
                labels: data.orderStatus.labels,
                datasets: [{
                    data: data.orderStatus.data,
                    backgroundColor: [
                        '#52C41A',
                        '#FAAD14',
                        '#1890FF',
                        '#FF4D4F'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                },
                cutout: '70%'
            }
        });
    }
}

// 初始化用户菜单交互
function initUserMenu() {
    const userMenuTrigger = document.getElementById('user-menu-trigger');
    const userDropdown = document.getElementById('user-dropdown');

    if (userMenuTrigger && userDropdown) {
        // 点击用户区域显示/隐藏下拉菜单
        userMenuTrigger.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('hidden');
        });

        // 点击页面其他区域隐藏下拉菜单
        document.addEventListener('click', function() {
            userDropdown.classList.add('hidden');
        });

        // 阻止下拉菜单内部点击事件冒泡
        userDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 个人信息按钮点击事件
        document.getElementById('personal-info-btn')?.addEventListener('click', function(e) {
            const collectUrl = '/userinfo'; // 用户信息地址
            window.open(collectUrl, 'userinfo');
        });

        // 退出登录按钮点击事件
        document.getElementById('logout-btn')?.addEventListener('click', function(e) {
            e.preventDefault();
            if(confirm('确定要退出登录吗？')) {
                loginOut();
            }
        });
    }
}

// 加载仪表盘数据（带降级处理）
async function loadDashboardData(apiService) {
    try {
        console.log('正在加载仪表盘数据...');
        const data = await apiService.getDashboardData();
        console.log('仪表盘数据加载成功:', data);
        
        // 更新概览卡片数据
        updateDashboardSummary(data);
        
        // 更新最近订单表格
        updateRecentOrdersTable(data.recentOrders);
        
        // 初始化/更新图表
        initCharts(data);
        
    } catch (error) {
        console.error('仪表盘数据加载失败，使用假数据:', error);
        // 使用假数据
        const mockData = MockData.dashboardData;
        updateDashboardSummary(mockData);
        updateRecentOrdersTable(mockData.recentOrders);
        initCharts(mockData);
    }
}

// 更新仪表盘概览数据
function updateDashboardSummary(data) {
    // 格式化数字显示（千位分隔符）
    const formatNumber = (num) => {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };
    
    // 更新各个统计卡片
    document.querySelector('.grid-cols-1 lg\\:grid-cols-4 .text-2xl.font-bold').textContent = `¥${formatNumber(data.todaySales)}`;
    document.querySelectorAll('.grid-cols-1 lg\\:grid-cols-4 .text-2xl.font-bold')[1].textContent = formatNumber(data.todayOrders);
    document.querySelectorAll('.grid-cols-1 lg\\:grid-cols-4 .text-2xl.font-bold')[2].textContent = formatNumber(data.activeUsers);
    document.querySelectorAll('.grid-cols-1 lg\\:grid-cols-4 .text-2xl.font-bold')[3].textContent = formatNumber(data.totalProducts);
}

// 更新最近订单表格
function updateRecentOrdersTable(orders) {
    const tableBody = document.querySelector('#dashboard-view table tbody');
    if (!tableBody) return;
    
    // 清空现有内容
    tableBody.innerHTML = '';
    
    // 添加新数据行
    orders.forEach(order => {
        const row = document.createElement('tr');
        row.className = 'table-row-hover';
        
        // 状态样式映射
        const statusClassMap = {
            'success': 'bg-success/10 text-success',
            'warning': 'bg-warning/10 text-warning',
            'info': 'bg-info/10 text-info',
            'danger': 'bg-danger/10 text-danger'
        };
        
        row.innerHTML = `
            <td class="py-3 px-4">${order.id}</td>
            <td class="py-3 px-4">
                <div class="flex items-center gap-2">
                    <img src="${order.avatar}" alt="${order.customer}头像" class="w-7 h-7 rounded-full">
                    <span>${order.customer}</span>
                </div>
            </td>
            <td class="py-3 px-4 font-medium">${order.amount}</td>
            <td class="py-3 px-4">
                <span class="px-2 py-1 rounded-full text-xs ${statusClassMap[order.statusType]}">${order.status}</span>
            </td>
            <td class="py-3 px-4 text-gray-500">${order.time}</td>
            <td class="py-3 px-4">
                <button class="text-primary hover:text-primary/80 mr-3">查看</button>
                <button class="text-gray-500 hover:text-gray-700">编辑</button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
}

// 加载商品列表数据（带降级处理）
async function loadProductsData(apiService, page = 1, pageSize = 10) {
    try {
        console.log('正在加载商品数据...');
        const data = await apiService.getProducts({ page, pageSize });
        console.log('商品数据加载成功:', data);
        
        // 更新商品表格
        updateProductsTable(data.list);
        
        // 更新分页信息
        updatePagination('products-view', data.page, data.pageSize, data.total);
        
    } catch (error) {
        console.error('商品数据加载失败，使用假数据:', error);
        // 使用假数据
        const mockData = {
            list: MockData.products,
            page: 1,
            pageSize: 10,
            total: 125
        };
        updateProductsTable(mockData.list);
        updatePagination('products-view', mockData.page, mockData.pageSize, mockData.total);
    }
}

// 更新商品表格
function updateProductsTable(products) {
    const tableBody = document.querySelector('#products-view table tbody');
    if (!tableBody) return;
    
    // 清空现有内容
    tableBody.innerHTML = '';
    
    // 添加新数据行
    products.forEach(product => {
        const row = document.createElement('tr');
        row.className = 'table-row-hover';
        
        // 状态样式映射
        const statusClassMap = {
            'success': 'bg-success/10 text-success',
            'gray': 'bg-gray-200 text-gray-500'
        };
        
        row.innerHTML = `
            <td class="py-3 px-4">
                <input type="checkbox" class="rounded text-primary focus:ring-primary">
            </td>
            <td class="py-3 px-4">
                <img src="${product.image}" alt="${product.name}" class="w-16 h-16 object-cover rounded">
            </td>
            <td class="py-3 px-4">
                <h4 class="font-medium">${product.name}</h4>
                <p class="text-sm text-gray-500 mt-1">SKU: ${product.sku}</p>
            </td>
            <td class="py-3 px-4">${product.category}</td>
            <td class="py-3 px-4 font-medium">${product.price}</td>
            <td class="py-3 px-4">${product.stock.toLocaleString()}</td>
            <td class="py-3 px-4">
                <span class="px-2 py-1 rounded-full text-xs ${statusClassMap[product.statusType]}">${product.status}</span>
            </td>
            <td class="py-3 px-4">
                <div class="flex gap-2">
                    <button class="text-primary hover:text-primary/80" title="查看">
                        <i class="fa fa-eye"></i>
                    </button>
                    <button class="text-gray-500 hover:text-gray-700" title="编辑">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="text-danger hover:text-danger/80" title="删除">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
}

// 加载订单列表数据（带降级处理）
async function loadOrdersData(apiService, page = 1, pageSize = 10) {
    try {
        console.log('正在加载订单数据...');
        const data = await apiService.getOrders({ page, pageSize });
        console.log('订单数据加载成功:', data);
        
        // 更新订单表格
        updateOrdersTable(data.list);
        
        // 更新分页信息
        updatePagination('orders-view', data.page, data.pageSize, data.total);
        
    } catch (error) {
        console.error('订单数据加载失败，使用假数据:', error);
        // 使用假数据
        const mockData = {
            list: MockData.dashboardData.recentOrders,
            page: 1,
            pageSize: 10,
            total: 500
        };
        updateOrdersTable(mockData.list);
        updatePagination('orders-view', mockData.page, mockData.pageSize, mockData.total);
    }
}

// 更新订单表格
function updateOrdersTable(orders) {
    const tableBody = document.querySelector('#orders-view table tbody');
    if (!tableBody) {
        console.log('订单表格不存在，创建基础表格结构');
        return;
    }
    
    // 清空现有内容
    tableBody.innerHTML = '';
    
    // 添加新数据行
    orders.forEach(order => {
        const row = document.createElement('tr');
        row.className = 'table-row-hover';
        
        // 状态样式映射
        const statusClassMap = {
            'success': 'bg-success/10 text-success',
            'warning': 'bg-warning/10 text-warning',
            'info': 'bg-info/10 text-info',
            'danger': 'bg-danger/10 text-danger'
        };
        
        row.innerHTML = `
            <td class="py-3 px-4">${order.id}</td>
            <td class="py-3 px-4">
                <div class="flex items-center gap-2">
                    <img src="${order.avatar}" alt="${order.customer}头像" class="w-7 h-7 rounded-full">
                    <span>${order.customer}</span>
                </div>
            </td>
            <td class="py-3 px-4 font-medium">${order.amount}</td>
            <td class="py-3 px-4">
                <span class="px-2 py-1 rounded-full text-xs ${statusClassMap[order.statusType]}">${order.status}</span>
            </td>
            <td class="py-3 px-4 text-gray-500">${order.time}</td>
            <td class="py-3 px-4">
                <button class="text-primary hover:text-primary/80 mr-3">查看</button>
                <button class="text-gray-500 hover:text-gray-700">编辑</button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
}

// 更新分页控件
function updatePagination(viewId, currentPage, pageSize, totalItems) {
    const viewElement = document.getElementById(viewId);
    if (!viewElement) return;
    
    // 计算总页数
    const totalPages = Math.ceil(totalItems / pageSize);
    
    // 更新分页信息文本
    const paginationInfo = viewElement.querySelector('.text-sm.text-gray-500');
    if (paginationInfo) {
        const startItem = (currentPage - 1) * pageSize + 1;
        const endItem = Math.min(currentPage * pageSize, totalItems);
        paginationInfo.textContent = `显示 ${startItem} 到 ${endItem} 条，共 ${totalItems} 条`;
    }
    
    // 更新分页按钮事件
    const paginationButtons = viewElement.querySelectorAll('.flex.items-center.gap-1 button:not([disabled])');
    paginationButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 获取页码（如果按钮文本是数字）
            const pageNum = parseInt(this.textContent.trim());
            if (!isNaN(pageNum) && pageNum !== currentPage) {
                if (viewId === 'products-view') {
                    loadProductsData(new ApiService(), pageNum, pageSize);
                } else if (viewId === 'orders-view') {
                    loadOrdersData(new ApiService(), pageNum, pageSize);
                }
            }
        });
    });
}

// 退出登录功能
function loginOut() {
    const apiService = new ApiService();

    apiService.loginOut()
        .then(success => {
            if (success) {
                handleLogoutSuccess();
            } else {
                alert('退出失败，请重试');
            }
        })
        .catch(error => {
            console.error('退出登录请求失败:', error);
            // 即使接口失败也执行本地退出
            handleLogoutSuccess();
        });
}

// 处理退出登录成功
function handleLogoutSuccess() {
    // 清除所有Cookie
    document.cookie.split(';').forEach(cookie => {
        const [name] = cookie.trim().split('=');
        document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
    });

    // 清除localStorage和sessionStorage
    localStorage.clear();
    sessionStorage.clear();

    // 跳转到登录页
    window.location.href = '/login_page';
}
    